'use strict';

function now() {
  return parseInt(Number(new Date()) / 1000, 10);
}
module.exports = app => {
  const { STRING, INTEGER, DATE } = app.Sequelize;

  const AuthorizationCode = app.model.define('authorizationCode', {
    code       : STRING,
    expiresAt  : DATE,
    redirectUri: STRING,
    scope      : STRING,
    clientId   : STRING,
    userId     : { type: INTEGER, allowNull: false },
  }, {
    createdAt: 'createdAt',
    updatedAt: 'updatedAt',
    tableName: 'zconnect-authorization-code',
  });

  // 保存code
  AuthorizationCode.saveAuthorizationCode = async function(code, client, user) {
    return await this.create({
      code       : code.authorizationCode,
      expiresAt  : code.expiresAt,
      redirectUri: code.redirectUri,
      scope      : code.scope || '',
      clientId   : client.clientId,
      userId     : user.lid,
    });
  };

  // 搜索code
  AuthorizationCode.queryAuthorizationCode = async function(params) {
    const where = Object.assign({
      expiresAt: {
        [app.Sequelize.Op.gt]: now(),
      },
    }, params);
    const res = await this.findOne({ where });
    return res;
  };

  // 搜索code 并删除
  AuthorizationCode.queryAuthorizationCodeAndRemove = async function(params) {
    const where = Object.assign({
      expiresAt: {
        [app.Sequelize.Op.gt]: now(),
      },
    }, params);
    const res = await this.findOne({ where });
    await this.destroy({ where });
    return res;
  };

  // 删除code
  AuthorizationCode.delAuthorizationCode = async function(code) {
    return await this.destroy({
      where: {
        code,
      },
    });
  };

  return AuthorizationCode;
};
